package com.lhz.collector.parse.lexer;

import com.lhz.collector.common.ConfBean;
import com.lhz.collector.common.SpringUtil;
import com.lhz.collector.parse.grok.CustomGrok;
import oi.thekraken.grok.api.Match;
import oi.thekraken.grok.api.exception.GrokException;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by LHZ on 2016/10/26.
 */
public class RegexLexer extends BaseLexer {
    private static CustomGrok grok;

    public RegexLexer(String pattern){
        ConfBean configuration= SpringUtil.getBean(ConfBean.class);
        String patternPath=configuration.getParsePattern();
        try {
            this.grok=new CustomGrok();
            grok.addPatternFromFile(patternPath);
            grok.compile(pattern);

        } catch (GrokException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> parse(String line) {
        Map<String, Object> resultMap =new HashMap<>();
        Match gm = grok.match(line);
        gm.captures();
        resultMap.putAll(gm.toMap());
        filter(resultMap);
        return resultMap;
    }
}
